package com.coolvania.auxilery;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import com.coolvania.app.Res;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

public class FolderPickerLauncher extends Activity implements DialogInterface.OnClickListener{
	private FolderPicker mFolderDialog;
	private int mNumItems;
	private String[] mFilePaths;

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(Res.layout.translucent_background);
        
        Bundle bundle = getIntent().getExtras();
        mNumItems = bundle.getInt("numItems");
        mFilePaths = new String[mNumItems];
        String mFilePath = "path0";
        for(int i = 0; i<mNumItems;i++)
        {
        	mFilePaths[i] = bundle.getString(mFilePath);
        	mFilePath = "path"+i+1;
        }
        
        mFolderDialog = new FolderPicker(this, this, 0);
        mFolderDialog.show();
    }

	public void onClick(DialogInterface dialog, int which) {
		
		String newPath = mFolderDialog.getPath();
		File mFile;
		File newFile;
		String newFileName;
		InputStream in = null;
		OutputStream out = null;
		
		for(int i = 0; i<mNumItems;i++)
		{
			mFile = new File(mFilePaths[i]);
			if(mFile.exists())
			{		
				try {
					in = new FileInputStream(mFile);
					newFileName = newPath + mFilePaths[i].substring(mFilePaths[i].lastIndexOf('/'));
					newFile = new File(newFileName);
					newFile.createNewFile();
					out = new FileOutputStream(newFileName);

					byte[] buffer = new byte[1024];
					int read;
					while ((read = in.read(buffer)) != -1) {
						out.write(buffer, 0, read);
					}
					in.close();
					out.flush();
					out.close();
				} catch (Exception e) {
					Log.e("tag", e.getMessage());
				}
			}
		}
		// TODO: maybe remove this
		in = null;
		out = null;
		
		Intent returnIntent = new Intent();
		setResult(RESULT_OK,returnIntent);
		finish();
	}
	
}
